package com.lanou3g.ptp.achievement.job;

import com.alibaba.dubbo.config.annotation.Reference;
import com.lanou3g.ptp.entity.Message;
import com.lanou3g.ptp.entity.Student;
import com.lanou3g.ptp.entity.Task;
import com.lanou3g.ptp.message.service.MessageService;
import com.lanou3g.ptp.signInDate.service.SignInDateService;
import com.lanou3g.ptp.task.service.TaskService;
import com.lanou3g.ptp.taskstudent.service.TaskStudentService;
import com.lanou3g.ptp.utils.DateUtils;
import com.lanou3g.ptp.vo.TemplateData;
import com.lanou3g.ptp.vo.WxTmplMsg;
import com.lanou3g.ptp.wx.service.WxService;
import org.quartz.JobExecutionContext;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class DiaryJob extends QuartzJobBean {

    @Reference
    private TaskService taskService;
    @Reference
    private TaskStudentService taskStudentService;
    @Reference
    private WxService wxService;
    @Reference
    private SignInDateService signInDateService;
    @Reference
    private MessageService messageService;

    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) {
        List<Task> tasks = taskService.findByStatus(Task.STATUS_RUNNING);
        for (Task task : tasks) {
            Long taskId = task.getId();
            boolean ifTodayInSignInDates = signInDateService.ifTodayInSignInDates(taskId);
            if (ifTodayInSignInDates) {
                List<Student> students = taskStudentService.findStudentsByTaskId(task.getId());
                for (Student student : students) {
                    Map<String, TemplateData> data = new HashMap<>();
                    String content = "今天还没有写日志,请尽快提交日志！（已提交日志请忽略）";
                    Date date = DateUtils.endTime(new Date());
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
                    String s = df.format(date);
                    data.put("keyword1", new TemplateData("日志提交"));
                    data.put("keyword2", new TemplateData(content));
                    data.put("keyword3", new TemplateData(s));
                    data.put("keyword4", new TemplateData("请尽快提交日志!"));
                    boolean result = wxService.sendMessage(student.getOpenId(), WxTmplMsg.TYPE_DIARY, data);
                    if (result) {
                        Message message = new Message();
                        message.setStudentId(student.getId());
                        message.setTaskId(taskId);
                        message.setContent(content);
                        messageService.saveDiaryMessage(message);
                    }
                }
            }
        }
    }
}
